package com.lee.common.base

import android.util.Log
import androidx.lifecycle.*
import com.lee.common.network.BaseResp
import com.lee.common.support.SingleLiveData
import kotlinx.coroutines.*
import java.lang.Exception

private const val TAG = "BaseViewModel"
open class BaseViewModel : ViewModel() {

     val refreshTrigger = MutableLiveData<Boolean>()
     val loading = MutableLiveData<Boolean>()


     protected val page = MutableLiveData<Int>()
     val refreshing = MutableLiveData<Boolean>()
     val moreLoading = MutableLiveData<Boolean>()
     val hasMore = MutableLiveData<Boolean>()
     val autoRefresh = MutableLiveData<Boolean>()//SmartRefreshLayout自动刷新标记


     open fun loadMore() {
          page.value = (page.value ?: 0) + 1
          moreLoading.value = true
     }

     /**
      * 自动刷新
      */
     fun autoRefresh() {
          autoRefresh.value = true
     }

     open fun refresh() {
          page.value = 0
          refreshing.value = true
     }

   /*  *//**
      * 处理分页数据
      *//*
     fun <T> mapPage(source: LiveData<BaseResp<T>>): LiveData<T> {
          return Transformations.map(source) {
               refreshing.value = false
               moreLoading.value = false
               hasMore.value = !(it?.data?.over ?: false)
               it.data ?: PageVO(1, ArrayList(), 0, true, 1, 20, 0)
          }
     }
*/
     open fun loadData() {
          refreshTrigger.value = true
          loading.value = true
     }


     val loadingLiveData = SingleLiveData<Boolean>()

     val errorLiveData = SingleLiveData<Throwable>()

     fun launch(
          block: suspend () -> Unit,
          error: suspend (Throwable) -> Unit,
          complete: suspend () -> Unit
     ) {
          loadingLiveData.postValue(true)
          viewModelScope.launch(Dispatchers.IO) {
               try {
                    block()
               } catch (e: Exception) {
                    Log.d(TAG, "launch: error ")
                    error(e)
               } finally {
                    complete()
               }
          }
     }



}